<template>
  <view class="appointment-box">
    <view class="title-box">
      <u-cell-group>
        <u-cell-item title="访客预约" :arrow="false" :title-style="{fontSize:'40rpx',fontWeight:700,color:'#000'}">
          <text class="but-right" @click="openGuestList">访问记录</text>
        </u-cell-item>
      </u-cell-group>
    </view>

    <view class="form" >
      <u-form :model="form" ref="uForm" :rules="rules" :label-style="{'paddingLeft':'10rpx'}">
        <view class="item-box">
          <u-form-item label="访客姓名" prop="visitorName">
            <u-input placeholder="请输入访客姓名" v-model="form.visitorName" />
          </u-form-item>
          <u-form-item label="手机号" prop="visitorTel">
            <u-input type="number" placeholder="请输入手机号" :maxlength="11" v-model="form.visitorTel" />
          </u-form-item>
        </view>
        <view class="item-box visit">
          <view @click="openPicker('visitorStartTime')">
            <u-form-item label="到访时间" label-position="top" :border-bottom="false">
              <u-picker mode="time" v-model="picker.star" :params="params"
                        @confirm="setDate($event,'visitorStartTime')"></u-picker>
            </u-form-item>
            {{form.visitorStartTime}}
          </view>
          <view @click="openPicker('visitorEndTime')">
            <u-form-item label="结束时间" label-position="top" :border-bottom="false">
              <u-picker mode="time" v-model="picker.end" :params="params"
                        @confirm="setDate($event,'visitorEndTime')"></u-picker>
            </u-form-item>
            {{form.visitorEndTime}}
          </view>
          <view class="jt-center">
            <u-icon name="arrow-right" size="25" color="#99999970" />
          </view>
        </view>
        <view class="item-box">
          <u-form-item label="来访目的">
            <view @tap="selectBol.visitorAim=true" class="wd-100">
              <u-section :title="displayLabel || '请选择'" :show-line="false" color="#999" :bold="false"
                         :sub-title="null"></u-section>
              <u-select v-model="selectBol.visitorAim" :list="seleCtome" @confirm="selctConfirm($event,'visitorAim', true)"></u-select>
            </view>
          </u-form-item>
          <u-form-item label="到访地址">
            <view @tap="selectBol.roomId=true" class="wd-100">
              <u-section :title="displayLabels || '请选择'" :show-line="false" color="#999" :bold="false"
                         :sub-title="null"></u-section>
              <u-select v-model="selectBol.roomId" :list="seleVisit" @confirm="selctConfirm($event,'roomId', false)"></u-select>
            </view>
          </u-form-item>
        </view>
        <view class="item-box">
          <u-form-item label="到访人数" prop="personNum">
            <u-input type="number" placeholder="请输入到访人数" :maxlength="11" v-model="form.personNum" />
          </u-form-item>
          <u-form-item label="车牌号" v-for="(item,index) in form.license" :key="index">
            <view class="cp-flex">
              <u-input placeholder="请输入车牌" v-model="form.license[index].value" disabled
                       @click="form.license[index].show = true" />
              <u-keyboard ref="uKeyboard" :tips="form.license[index].tips" mode="car" v-model="form.license[index].show"
                          @change="carKey($event,index)" @confirm="keyboardOK(index)"
                          @backspace="triBackspace(index)"></u-keyboard>
            </view>
          </u-form-item>
          <view class="item-text" @click="addLicense">
            {{itemText}}
          </view>
        </view>
      </u-form>
    </view>
    <view class="po-but">
      <u-button type="primary" shape="circle" @click="submit">预约</u-button>
    </view>
  </view>
</template>

<script>
import {
  visitorManageSubmitForm
} from '@/api/wit/visitorManageApi.js'
import {
  householdinfo
} from '@/api/base/householdinfoApi.js'

import { mapGetters } from 'vuex';

export default {
  data() {
    return {
      displayLabel: '',
      displayLabels: '',
      labelWidth: 0, // 初始值为 0
      form: {
        visitorName: '',
        proprietorId: '',
        visitorTel: '',
        visitorStartTime: '',
        visitorEndTime: '',
        visitorAim: '',
        roomId: '',
        license: [{
          show: false,
          tips: '',
          value: ''
        }]
      },
      sr: '',
      seleCtomes: [],  // 来访目的选择项
      show: false,
      itemText: '+添加更多信息',
      seleVisit: [],
      seleCtome: [],
      selectBol: {
        proprietorId: false,
        visitorAim: false,
        roomId: false
      },
      picker: {
        star: false,
        end: false
      },
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      rules: {
        visitorName: [{
          required: true,
          message: '请输入姓名',
          trigger: ['change', 'blur'],
        }],
        visitorTel: [{
          required: true,
          max: 11,
          message: '请输入手机号',
          trigger: ['change', 'blur']
        },
          {
            pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '手机号格式错误',
            trigger: ['blur', 'change']
          }
        ]
      },

      options: ['选项1', '选项2', '选项3'],
      customStyle: {
        borderRadius: '50rpx',
        textAlign: 'center',
        padding: '7rpx 20rpx'
      }
    }
  },
  mounted() {

    this.$nextTick(()=>{
      this.$refs.uForm.setRules(this.rules);
    }),
        this.getVisitorAims();  // 获取来访目的列表
    this.getOptions();
  },
  computed: {
    ...mapGetters(['user_info']),
  },
  methods: {
    getOptions() {
      this.seleCtome =  this.$dictTools.dictList('VISITOR_AIM').map(e=>({label:e.text,value:e.value}));
      console.log(this.seleCtome);
    },
    getVisitorAims() {
      const proprietorId = this.user_info.id;
      console.log(this.user_info,'this.user_info')
      householdinfo({ proprietorId })
          .then(response => {
            const newSelectData = response.map(data => ({
              value: data.roomId,
              label: data.roomInfo
            }));

            this.seleVisit = newSelectData;
            console.log(this.seleVisit,'this.seleVisit');
          })
          .catch(error => {
            console.error('获取来访目的列表失败', error);
          });
    },
    openGuestList(){
      uni.navigateTo({
        url:'/subPack/guestList'
      })
    },
    submit() {
      this.$refs.uForm.validate().then(res => {
        this.form.proprietorId = this.user_info.id;
        visitorManageSubmitForm(this.form, !this.form.id).then(respond => {
          uni.$emit('formBack', {
            data: respond
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            })
          }, 800)
        })
      })
    },
    openPicker(type) {
      this.picker.star = type === 'visitorStartTime';
      this.picker.end = type === 'visitorEndTime';
    },
    setDate(e, type) {
      const {
        year,
        month,
        day
      } = e
      const dateStr = `${year}-${month}-${day}`;
      this.form[type] = dateStr;
    },
    selctConfirm(e, type, isVisitorAim) {
      if (isVisitorAim) {
        this.form[type] = e[0].value;
        this.displayLabel = e[0].label;
      } else {
        this.form[type] = e[0].value;
        this.displayLabels = e[0].label;
      }
    },
    carKey(e, index) {
      this.form.license[index].tips += e
    },
    addLicense() {
      this.form.license.push({
        show: false,
        tips: '',
        value: ''
      })
    },
    keyboardOK(index) {
      this.form.license[index].value = this.form.license[index].tips
    },
    triBackspace(index) {
      const str = this.form.license[index].tips;
      this.form.license[index].tips = str.substring(0, str.length - 1)
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕

}
</script>

<style lang="scss" scoped>
.appointment-box{
  height: calc(100vh - 250rpx);
  overflow: auto;
}
.po-but {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 30rpx 20rpx;
  box-shadow: 0px -5px 5px -5px rgba(0, 0, 0, 0.2);
}

.item-box {
  position: relative;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
  background-color: #fff;

  &.visit {
    display: flex;
    justify-content: space-between;
  }

  .jt-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: no-repeat;
  }

  .item-text {
    line-height: 85rpx;
    text-align: center;
    color: $-color-but-wy+30;
  }
}

.cp-flex {
  display: flex;
}

.but-right {
  border: 1px solid $-color-but-wy;
  color: $-color-but-wy;
  border-radius: 50rpx;
  text-align: center;
  padding: 7rpx 20rpx;
}

/deep/.u-form-item {
  padding: 10rpx 10rpx 10rpx 0;

  .u-form-item--left__content__label {
    padding: 0 !important;
  }
  .u-form-item--left{
    flex:0 0 auto !important;
    width: 160rpx !important;
  }
  .u-form-item__message{
    padding-left: 160rpx !important;
  }
}
/deep/.u-flex .u-section__title__text{
  color: #000 !important;
}
</style>